﻿using AutoMapper;
using MediatR;
using SmartCity.ProcessEngine.Api.Write.Application.Command.FormNodeConfig;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using System.Transactions;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.Api.Write.Application.CommandHandler.FormNodeConfig
{
    public class CreateFormNodeCfgHandler : IRequestHandler<CreateFormNodeCfgCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<FormNodeConfigModel> nodeCfgRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateFormNodeCfgHandler> logger;

        public CreateFormNodeCfgHandler(IBaseRepository<FormNodeConfigModel> nodeCfgRepo,IMapper mapper,ILogger<CreateFormNodeCfgHandler> logger)
        {
            this.nodeCfgRepo = nodeCfgRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(CreateFormNodeCfgCommand request, CancellationToken cancellationToken)
        {
            var entities = nodeCfgRepo.GetAll().Where(x=>x.FormId==request.FormId).ToList();
            foreach (var entity in entities) {
                entity.IsDeleted = true;//循环把列表里所有的数据逻辑删除状态改为true
            }

            //第一步,清理指定表单的所有节点配置数据



            //第二步,批量添加本次配置的流程节点集合  request.createNodeCfgDtos.
            var models = mapper.Map<List<FormNodeConfigModel>>(request.createNodeCfgDtos); //把请求命令里的dto列表转成实体列表 
            foreach (var model in models) {
                model.Id = YitIdHelper.NextId();
            }
            int r0 = 0;
            int r1 = 0;

            //开启事务,批量修改和添加
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
                try
                {
                    r0 =await nodeCfgRepo.UpdateRangeAsync(entities);
                    r1 = await nodeCfgRepo.CreateRangeAsync(models);
                    tran.Complete();//提交分布式事务
                }
                catch (Exception e)
                {
                    logger.LogError($"事务中添加流程节点配置失败回滚,{e.Message}");
                    throw;
                }
            }
            if (r1 > 0)
            {
                return new ApiResult<int>().AddSuccess("流程节点配", r1);
            }
            else {
                return new ApiResult<int>().AddFail("流程节点配");
            }
        }
    }
}
